package data.join.com.database.bean;

import java.io.File;
import java.util.List;

import data.join.com.database.GreenDao;
import data.join.com.http.GetImage;
import data.join.com.utils.FileUtils;

/**
 * Created by Administrator on 2016/7/1.
 */
public class ImageDBPref {
    private String TAG = "ImageDBPref";
    private static ImageDBPref mImageDBPref;
    private ImageBeanDao imageBeanDao;

    private ImageDBPref() {
        imageBeanDao = GreenDao.getInstance().sDaoSession.getImageBeanDao();
    }

    public static ImageDBPref getInstance(){
        if(mImageDBPref == null){
            mImageDBPref = new ImageDBPref();
        }
        return mImageDBPref;
    }

    public ImageBean insertImageBean(ImageBean image){
        ImageBean bean = null;

        imageBeanDao.insert(image);

        return bean;
    }

    public void deleteImageBean(ImageBean image){
        FileUtils.deleteFile(image.thumbnail);
        imageBeanDao.delete(image);
    }

    public boolean existImageByPath(String path){

        long count = imageBeanDao.queryBuilder().where(ImageBeanDao.Properties.SrcPath.eq(path)).count();

        return count > 0;
    }

    public List<ImageBean> getImageList(){
        List<ImageBean> list;

        list = imageBeanDao.loadAll();

        return list;
    }

    public GetImage getImageListByHttp(int limit, int offset){
        GetImage getImage = new GetImage();

        List<ImageBean> list = imageBeanDao.queryBuilder().orderDesc(ImageBeanDao.Properties.Time).offset(offset).limit(limit).list();

        getImage.setImageList(list);

        getImage.count = (int)imageBeanDao.count();

        getImage.limit = limit;
        getImage.offset = offset;
        return getImage;
    }

    public void clearNotExistFile(){
        List<ImageBean> list = getImageList();

        for(ImageBean image:list){
            if(!new File(image.srcPath).exists()){
                deleteImageBean(image);
            }
        }
    }

    public boolean deleteImageById(Long id){
        imageBeanDao.deleteByKey(id);
        return false;
    }

}
